'''
Created on 11/11/2013

@author: Lior Friedman
'''
import random

from map_problem import *
from aima import search
from functools import partial

def IsReachable(road_map, initial, goal):
    '''You must implement this method.
    It will return True if and only if there is a route linking initial and goal.
    The route may be indirect, i.e. I->X->G'''
    print 'IsReachable {} -> {}, result: '.format(initial, goal)
    problem = MapProblem(initial, goal, road_map)
    node = search.depth_first_graph_search(problem)
    # TRM debug?
    if node:
        path = node.path()
        print "\tdistance = {}, time = {}".format(
                                                sum(node.action.distance for node in path if node.action),
                                                sum(node.action.CalcTime() for node in path if node.action))
    else:
        print "not reachable!"
    return node != None

def GenerateProblemSet(road_map, k= 100):
    '''You must implement this method.
    This method returns a list of (initial,goal) tuples such that initial is reachable from goal and vice-versa.
    k is the total amount of pairs to add. Pairs must be chosen randomly. '''
    problem_set = []
    while len(problem_set) < 100:
        j1, j2 = random.choice(road_map.junctions), random.choice(road_map.junctions)
        if (j1 != j2) and IsReachable(road_map, j1.key, j2.key) and IsReachable(road_map, j2.key, j1.key):
            problem_set.append((j1.key, j2.key))

    return problem_set

def SaveToFile(filename, problem_set):
    '''saves your Problem set to a CSV file.
    The format is <pair i initial>, <pair i goal>'''
    file_ptr = open(filename, 'w')
    for pair in problem_set:
        file_ptr.write(str(pair[0]) + ',' + str(pair[1]) + '\n')
    file_ptr.close()

def LoadfFromFile(filename, conv_func = int):
    '''saves your Problem set to a CSV file.
    The format is <pair i initial>, <pair i goal>'''
    return [[conv_func(x) for x in line.split(',')] for line in open(filename, 'r')]